//
//  VCItemView.m
//  VideoCollage
//
//  Created by Mac on 2018/6/22.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "VCItemView.h"
#import "AVAsset+STTools.h"
#import "NSBundle+STSystemTool.h"
@interface VCItemView()

@end
@implementation VCItemView

- (instancetype)initWithRank:(NSInteger)rank{
    if (self == [super init]) {
        self.rank = rank;
        self.itemInset = VCItemViewDefultItemInset;
        self.backgroundColor = UIColor.whiteColor;
        self.arrAvAssetArray = NSMutableArray.new;
        self.frame = CGRectMake(VCItemleftInset, 0, VCItemViewDefultWith, VCItemViewDefultWith);
    }
    return self;
}
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    if (self.rank) {
        if (self.itemImageViewArray.count) {
            [self updateItemFrame];
        }else{
            [self configSubView];
        }
    }
}
- (VCItemSizeModel *)sizeModel{
    if (!_sizeModel) {
        _sizeModel = VCItemTools.defultSizeModel;
    }
    return _sizeModel;
}
- (CGFloat)maxWith{
    if (!_maxWith) {
        _maxWith = 0.8 * UIScreenWidth;
    }
    return _maxWith;
}
- (void)updateItemFrame{
    VCItemSizeModel * model = self.sizeModel; 
    CGFloat maxWithd = self.maxWith;
    CGFloat minSizeLength = MIN(model.size.width, model.size.height);
    CGFloat maxSizeLength = MAX(model.size.width, model.size.height);
    
    CGFloat bili = minSizeLength / maxSizeLength;
    CGSize finshSize  = CGSizeZero;
    if (maxSizeLength == model.size.width) {
        //长 为 最大 将长 缩小 为 maxWithd
        CGFloat dealHeight = maxWithd * bili;
        
        finshSize = CGSizeMake(maxWithd, dealHeight);
    }else{
        //高 为 最大 将长 缩小 为 maxWithd
        CGFloat dealWith = maxWithd * bili;
        
        finshSize = CGSizeMake(dealWith, maxWithd);
    }

    CGPoint center = self.center;
    self.layer.frame = CGRectMake(center.x - finshSize.width/2, center.y - finshSize.height/2, finshSize.width, finshSize.height);
    self.layer.cornerRadius = model.cornerRadius;
    self.itemFrameArray = [VCItemTools frameWithRank:self.rank itemInset:model.insetValue superSize:finshSize];
    for (NSInteger i = 0; i < self.itemFrameArray.count; i ++) {
        VCItemFrameModel * model = self.itemFrameArray[i];
        UIImageView * imageView = self.itemImageViewArray[i];
        //配置布局
        imageView.width = model.scaleWitdh * self.width;
        imageView.height = model.scaleHeight * self.height;
        imageView.center = model.center;
        [imageView st_setDottedLineBrderWidth:1 borderColor:TM_lineColor];
    }
}
- (void)hideNOResultButton{
    for (VCImageView * imageView in self.itemImageViewArray) {
        if (imageView.isNotChosed) {
            imageView.hidden = YES;
        }
    }
}
- (void)showAllButton{
    for (VCImageView * imageView in self.itemImageViewArray) {
        imageView.hidden = NO;
    }
}
- (BOOL)isAllImage{
    BOOL isAllImage = YES;
    for (TZAssetModel * model in self.assetModles) {
        if (model.type != TZAssetModelMediaTypePhoto) {
            isAllImage = NO;
        }
    }
    return isAllImage;
}
- (void)setAssetModles:(NSArray<TZAssetModel *> *)assetModles{
    _assetModles =  assetModles;
    //加载视频 asset
    for (TZAssetModel * model in assetModles) {
        if (model.didBegin && model.avasset) {
            //添加已经加载和准备好的avasset
            [self.arrAvAssetArray addObject:model.avasset];
        }
        if (model.type == TZAssetModelMediaTypeVideo && !model.didBegin && !model.avasset) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //开始准备 视频资源
                [self exporAndStartPrepreModel:model];
            });
        }
        
    }
    for (UIImageView * button in self.itemImageViewArray) {
        button.hidden = NO;
        [button setImage:DefultAddImage];
    }
    for (NSInteger i = 0; i < assetModles.count; i ++) {
        TZAssetModel * model = assetModles[i];
        VCImageView * imageView ;
        if (i < self.itemImageViewArray.count) {
            imageView = self.itemImageViewArray[i];
            [imageView setImage:model.cachedImage];
            [self loadOriginImageWithImageView:imageView model:model];
            
        }
        
    }
    
}
//加载资源的原图
- (void)loadOriginImageWithImageView:(VCImageView*)imageView model:(TZAssetModel*)model{
    VCImageView *  button = imageView;
    if (model.requestID) {
        [[PHImageManager defaultManager] cancelImageRequest:model.requestID];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        model.requestID =   [[TZImageManager manager] getOriginalPhotoReturnIDWithAsset:model.asset newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            if (![info[PHImageResultIsDegradedKey] boolValue]) {
                //原图
                dispatch_async(dispatch_get_main_queue(), ^{
                    [button setImage:model.cachedImage];
                    [button st_setDottedLineBrderWidth:1 borderColor:UIColor.clearColor];
                });
                
            }
        }];
        
    });
}
//导出视频和准备视频
- (void)exporAndStartPrepreModel:(TZAssetModel*)model{
    if (model.requestID) {
        [[PHImageManager defaultManager] cancelImageRequest:model.requestID];
    }
    PHImageRequestID requestId  = [[TZImageManager manager] getReturnIDVideoOutputPathWithAsset:model.asset success:^(NSString *outputPath) {
        
        AVAsset * topAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:outputPath]];
        model.path = outputPath;
        [topAsset whenProperties:@[@"tracks"] areReadyDo:^{
            model.avasset = topAsset;
            model.didBegin = YES;
            bool judgeAllPathLoad = self.judgeAllPathLoad;
            bool judgeAllAvAssetReady = self.judgeAllAvAssetReady;
            if (self.allAvAssetReady && judgeAllPathLoad && judgeAllAvAssetReady) {
                self.allAvAssetReady(YES);
            }
            [self.arrAvAssetArray addObject:topAsset];
        }];
        
        
        
    } failure:^(NSString *errorMessage, NSError *error) {
        
    }];
    
    model.requestID = requestId;
}
- (BOOL)judgeAllPathLoad{
    BOOL isAllLoad = YES;
    for (TZAssetModel * model in self.assetModles) {
        //获取的 outputPath
        if (model.type == TZAssetModelMediaTypeVideo && model.path.length == 0) {
            isAllLoad = NO;
        }
        
    }
    return isAllLoad;
}
- (CGFloat)shortDuring{
    CGFloat during = 999;
    for (TZAssetModel * model in self.assetModles) {
        PHAsset * asset = model.asset;
        CGFloat aseetDuring = asset.duration;
        during = MIN(during, aseetDuring);
    }
    return during;
}
- (CMTime)shortDuringCMTime{
    CMTime during = self.assetModles.firstObject.avasset.duration;
    for (TZAssetModel * model in self.assetModles) {
        CMTime duration = model.avasset.duration;
        during = CMTimeMinimum(during, duration);
    }
    return during;
}
- (BOOL)judgeAllAvAssetReady{
    BOOL isAllReady = YES;
    for (TZAssetModel * model in self.assetModles) {
        //获取的 outputPath
        if (model.type == TZAssetModelMediaTypeVideo && !model.didBegin) {
            isAllReady = NO;
        }
        
    }
    //    return YES;
    return isAllReady;
}
- (VCImageView *)nearNoresultImageView{
    for (VCImageView * imageView in self.itemImageViewArray) {
        if (imageView.isNotChosed) {
            return imageView;
        }
    }
    return nil;
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.itemFrameArray = [VCItemTools frameWithRank:self.rank itemInset:self.itemInset superSize:self.size];
    self.itemImageViewArray = NSMutableArray.new;
    for (NSInteger i = 0; i < self.itemFrameArray.count; i ++) {
        VCItemFrameModel * model = self.itemFrameArray[i];
        VCImageView * imagView = [[VCImageView alloc] initWithImage:DefultAddImage];
        imagView.image = DefultAddImage;
        [imagView st_setDottedLineBrderWidth:1 borderColor:UIColor.redColor];
        imagView.clipsToBounds = YES;
        imagView.contentMode = UIViewContentModeScaleAspectFill;
        
        //配置布局
        imagView.width = model.scaleWitdh * self.width;
        imagView.height = model.scaleHeight * self.height;
        imagView.center = model.center;
        imagView.userInteractionEnabled = YES;
        UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSelctedImageView:)];
        [imagView addGestureRecognizer:ges];
        [self addSubview:imagView];
        [self.itemImageViewArray addObject:imagView];
        
    }
}
#pragma mark --Action Method
//废弃
- (void)onSlectedButton:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onSlectedView:item:)]) {
        [self.delegate onSlectedView:self item:sender];
    }
}
- (void)onSelctedImageView:(UITapGestureRecognizer*)tap{
    if (self.delegate && [self.delegate respondsToSelector:@selector(onSlectedView:item:)]) {
        [self.delegate onSlectedView:self item:(id)tap.view];
    }
}
@end

